package com.zhx.threadcoreknowledge.threadobjectclasscommonmethod;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-03 16:57
 * 用途         ： 使用wait和notify交替答应0~100的奇偶数
 */
public class CountNumTo100Demo3 {

    private  static int maxnum = 100;

    private static int count = 0;

    private static Object lock = new Object();

    static class TurningPrintFunction implements Runnable{
        @Override
        public void run() {
            while(count<=maxnum){
                synchronized (lock){
                    System.out.println(Thread.currentThread().getName()+"线程打印:" + count++);

                    lock.notify();

                    if(count<=maxnum){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        TurningPrintFunction printFunction1 = new TurningPrintFunction();
        TurningPrintFunction printFunction2 = new TurningPrintFunction();

        Thread manThread = new Thread(printFunction1,"奇数");
        Thread girlThread = new Thread(printFunction2,"偶数");

        girlThread.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        manThread.start();
    }
}
